package cn.sail.spring.mvc.controller;

import cn.sail.spring.mvc.content.Content;
import cn.sail.spring.mvc.util.StringUtil;
import cn.sail.spring.mvc.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


@Controller
@RequestMapping("file")
@Api(tags = "文件相关业务接口")
public class FileController {

    @RequestMapping(value = "upload", method = RequestMethod.POST
            , headers = "content-type=multipart/form-data"
            , consumes = "multipart/*")
    @ApiOperation("文件上传接口")
    @ResponseBody
    public ResultVO upload(@ApiParam("文件对象") MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        //组合保存地址
        String dateDir = StringUtil.getUploadDateDir();
        File dirFile = new File(Content.UPLOAD_PATH +dateDir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String fileName = StringUtil.getTimeStampString()+"-"+file.getOriginalFilename();
        String filePath = dateDir+fileName;

        try {
            //读取文件保存到具体目录中
            file.transferTo(new File(Content.UPLOAD_PATH+filePath));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        }
        request.getSession().setAttribute("uploadURL",filePath);
        ResultVO resultVO = new ResultVO();
        resultVO.setMsg("文件上传成功");
        return resultVO;
    }

    @RequestMapping(value = "download", method = RequestMethod.GET)
    @ApiOperation("文件下载接口")
    @ResponseBody
    public ResultVO download(HttpServletRequest request, HttpServletResponse response){
        String filename = (String) request.getSession().getAttribute("uploadURL");
        System.out.println(filename);
        if(filename == null || filename.length() == 0){
            throw new RuntimeException("你还未上传文件");
        }
        File file = new File(Content.UPLOAD_PATH+filename);
        System.out.println(file.length());
        response.reset();
        //设置返回文件大小
        response.setContentLength(Integer.valueOf(file.length()+""));
        String suffix = filename.substring(filename.lastIndexOf(".")+1,filename.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis()+"."+suffix);
        writeFileToResponse(file,response);
        ResultVO resultVO = new ResultVO();
        resultVO.setMsg("文件下载成功");
        return resultVO;
    }



    /**
     * 将文件流读出放入至指定的response
     * @param file
     * @param response
     */
    private void writeFileToResponse(File file,HttpServletResponse response){
        byte[] buff = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            ServletOutputStream outputStream = response.getOutputStream();
            int i = bis.read(buff);
            while(i != -1){
                try {
                    outputStream.write(buff, 0, i);
                    i = bis.read(buff);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("文件下载失败");
                }
            }
            bis.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件下载失败");
        }

    }

    @RequestMapping(value = "downloadTest", method = RequestMethod.GET)
    @ApiOperation("文件下载测试接口")
    @ResponseBody
    public ResultVO downloadTest(HttpServletRequest request, HttpServletResponse response) {
        try {
            //获取页面输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //读取文件
            byte[] bytes = FileUtils.readFileToByteArray(new File("C:\\Users\\dell\\Desktop\\毕设材料\\微信图片.jpg"));
            //向输出流写文件
            //写之前设置响应流以附件的形式打开返回值,这样可以保证前边打开文件出错时异常可以返回给前台
            response.setHeader("Content-Disposition", "attachment;filename=123.jpg");
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            ResultVO resultVO = new ResultVO();
            resultVO.setMsg("文件下载成功");
            return resultVO;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件下载失败");
        }
    }


}
